//
//  HSYFillInformationViewController.m
//  HSY
//
//  Created by 陈浩 on 2017/4/6.
//  Copyright © 2017年 金开门. All rights reserved.
//

#import "HSYFillInformationViewController.h"
#import "HSYFillInformationModel.h"
#import "HexColor.h"
#import "UIImage+Tools.h"
#import "BQActivityView.h"
#import "HSYImproveStoreInformationRequest.h"
#import "HSYSelectProvinceViewController.h"
#import "HSYShopPhotosViewController.h"
#import "UIImagePickerController+Block.h"
#import "HCGDatePickerAppearance.h"
#import "NSString+Validation.h"

@interface HSYFillInformationViewController ()


@property (weak, nonatomic) IBOutlet UITextField *shopAbbreviationTextField;
@property (weak, nonatomic) IBOutlet UITextField *shopLocationTextField;
@property (weak, nonatomic) IBOutlet UITextField *shopDetailedAddressTextField;
@property (weak, nonatomic) IBOutlet UITextField *licenceStartDateTextFiled;
@property (weak, nonatomic) IBOutlet UITextField *licenceEndDateTextFIled;
@property (weak, nonatomic) IBOutlet UITextField *licenceNOTextFiled;


@property (weak, nonatomic) IBOutlet UIImageView *businessLicenseImageView;

@property (weak, nonatomic) IBOutlet UIButton *settlementTypeToPublicBtn;
@property (weak, nonatomic) IBOutlet UIButton *selectProvincesBtn;
@property (weak, nonatomic) IBOutlet UIButton *settlementTypeToPrivateBtn;
@property (weak, nonatomic) IBOutlet UIButton *takePhotoBtn;

@property(nonatomic,strong)HSYFillInformationModel *requestModel;

@end

@implementation HSYFillInformationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self.leftAreaLBtn setImage:[UIImage imageNamed:@"left"]  forState:UIControlStateNormal];
    [self.titleButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.titleButton setTitle:@"填写店铺资料" forState:UIControlStateNormal];
    
    [self.settlementTypeToPublicBtn setTitleColor:[UIColor colorWithHexString:@"6284dd"] forState:UIControlStateSelected];
    [self.settlementTypeToPrivateBtn setTitleColor:[UIColor colorWithHexString:@"6284dd"] forState:UIControlStateSelected];
    
    
    [self settlementTypeBtn:self.settlementTypeToPublicBtn backgroundColor:[UIColor whiteColor] borderColor:[UIColor colorWithHexString:@"bebebe"]];
    [self settlementTypeBtn:self.settlementTypeToPrivateBtn backgroundColor:[UIColor whiteColor] borderColor:[UIColor colorWithHexString:@"bebebe"]];
    
    
    [self settlementTypeToPrivateBtnClick:nil];
    
    [self fillbackIfNeed];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)fillbackIfNeed{
    self.shopAbbreviationTextField.text = [HSYUserCenter instatce].appBizShop.shortName;//简称
    self.shopLocationTextField.text = [HSYUserCenter instatce].appBizShop.districtName; //选择地区
    self.shopDetailedAddressTextField.text = [HSYUserCenter instatce].appBizShop.address; //街道
    self.licenceNOTextFiled.text = [HSYUserCenter instatce].appBizShop.licenceNO;
    
    long startDate = [[HSYUserCenter instatce].appBizShop.licenceStartDate longLongValue]/1000;
    long endDate = [[HSYUserCenter instatce].appBizShop.licenceEndDate longLongValue]/1000;
    
    if (startDate > 0) {
        self.requestModel.licenceStartDate = [NSString dateStringFrom1970:startDate formatter:@"yyyy-MM-dd"];
        self.licenceStartDateTextFiled.text = [NSString dateStringFrom1970:startDate formatter:@"yyyy年MM月dd日"];
    }
    
    if (endDate > 0) {
        self.requestModel.licenceEndDate = [NSString dateStringFrom1970:endDate formatter:@"yyyy-MM-dd"];
        self.licenceEndDateTextFIled.text = [NSString dateStringFrom1970:endDate formatter:@"yyyy年MM月dd日"];
    }
    
    self.requestModel.districtCode = [HSYUserCenter instatce].appBizShop.districtCode;
    self.requestModel.isPublic = [HSYUserCenter instatce].appBizShop.isPublic;
    
    if ([HSYUserCenter instatce].appBizShop.isPublic) {
        [self settlementTypeToPublicBtnClick:nil];
    }

}



#pragma mark - 重载父类方法 -
- (void)setupNavigationBarBackgroundImage{
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithColor:[UIColor clearColor] size:CGSizeMake(1, 1)]  forBarMetrics:UIBarMetricsDefault];
    
    self.navigationController.navigationBar.shadowImage = [UIImage new];
}

-(void)handleGoBackEvent:(UIButton *)sender{
    if (self.navigationController.childViewControllers.count <= 1) { //模态
        [self.navigationController dismissViewControllerAnimated:YES completion:nil];
    }else{
        [super handleGoBackEvent:sender];
    }
}

#pragma mark - 懒加载requestModel -
-(HSYFillInformationModel *)requestModel{
    if (!_requestModel) {
        _requestModel = [[HSYFillInformationModel alloc] init];
    }
    
    return _requestModel;
}


//设置btn样式
-(void)settlementTypeBtn:(UIButton *)btn  backgroundColor:(UIColor *)bgcolor borderColor:(UIColor *) borderColor{
    btn.clipsToBounds = YES;
    btn.layer.borderColor = borderColor.CGColor;
    btn.backgroundColor = bgcolor;
    btn.layer.borderWidth = 0.5;
}

#pragma mark - Action Methods -
//点击下一步
- (IBAction)nextStepBtnClick:(id)sender {
    [self.view endEditing:YES];
    if (![self checkDataIntegrity]) return; //检查信息是否完善
    
    self.requestModel.mainStoreID = [HSYUserCenter instatce].appBizShop.shopID;
    
    HSYImproveStoreInformationRequest *task = [[HSYImproveStoreInformationRequest alloc] init];
    task.shortName = self.requestModel.shortName;
    task.mainStoreID = self.requestModel.mainStoreID;
    task.districtCode = self.requestModel.districtCode;
    task.address = self.requestModel.address;
    task.isPublic = self.requestModel.isPublic;
    task.licenceEndDate = self.requestModel.licenceEndDate;
    task.licenceStartDate = self.requestModel.licenceStartDate;
    task.licenceNO = self.requestModel.licenceNO;
    
    UIImage *image = self.businessLicenseImageView.image;
    NSData *data = UIImageJPEGRepresentation(image, 0.1);
    
    task.fileData = data;
    
    [BQActivityView showActiviTy];
    
    __weak typeof(self)weakSelf = self;
    [HSYNetworkManager POST:task success:^(HSYResponse *response) {
        [BQActivityView hideActiviTy];

        if (response.resultCode == HSY_REQUEST_CODE_SUCCESS) {
            //保存商铺信息
            [HSYUserCenter instatce].appAuUser.auStep = 1;
            [HSYUserCenter instatce].appBizShop.isPublic = weakSelf.requestModel.isPublic;
            [[HSYUserCenter instatce] saveUserModelToDocuments];
            
            //推出下一步操作
            [weakSelf pushToFillInShopPhotos];
        }else{
            [weakSelf showMessage:response.resultMessage];
        }
    } failure:^(NSError *error) {
        [BQActivityView hideActiviTy];
        
        if (error.code != NSURLErrorCancelled) {
            [weakSelf showMessage:@"请求超时"];
        }
    }];
}

//检查信息是否完善
-(BOOL)checkDataIntegrity
{
    self.requestModel.shortName = self.shopAbbreviationTextField.text;
    self.requestModel.address = self.shopDetailedAddressTextField.text;
    self.requestModel.licenceNO = self.licenceNOTextFiled.text;
    
    
    if (!self.requestModel.shortName.length) {
        [self showMessage:@"请填写商铺简称"];
        return NO;
    }else if(![self.requestModel.shortName isValidShopShortName]){
        [self showMessage:@"店铺名称限制为5-25个字数"];
        return NO;
    }
    
    if (!self.requestModel.address.length) {
        [self showMessage:@"请填写详细地址"];
        return NO;
    }else if(![self.requestModel.address isValideAddress]){
        return NO;
    }
    
    if (!self.settlementTypeToPublicBtn.selected && !self.settlementTypeToPrivateBtn.selected) {
        [self showMessage:@"请选择结算类型"];
        return NO;
    }
    
    if (!self.requestModel.districtCode.length) {
        [self showMessage:@"请选择商铺所在地"];
        return NO;
    }
    
    if ( self.requestModel.isPublic == 1) {
        if (self.requestModel.licenceNO.length == 0) {
            [self showMessage:@"对公营业执照号必填"];
            return NO;
        }else if(![self.requestModel.licenceNO isValideLicenceNO]){
            [self showMessage:@"请输入正确营业执照号"];
            return NO;
        }
        
        if (self.requestModel.licenceStartDate.length == 0) {
            [self showMessage:@"对公营业执照开始日期必填"];
            return NO;
        }

        if (!self.businessLicenseImageView.image) {
            [self showMessage:@"对公营业执照照片必填"];
            return NO;
        }

        
    }

    
    return YES;
}

//选中城市
- (IBAction)selectProvincesBtnClick:(id)sender {
    [self.view endEditing:YES];
    
    HSYSelectProvinceViewController *vc = [[HSYSelectProvinceViewController alloc] init];
    
    __weak typeof(self)weakSelf = self;
    [vc getProvinceCityCountyinfo:^(NSString *title, NSString *code) {
        weakSelf.shopLocationTextField.text = title;
        weakSelf.requestModel.districtCode = code;
    }];
    
    [self.navigationController pushViewController:vc animated:YES];
}

//设置 公开 / 私有
- (IBAction)settlementTypeToPublicBtnClick:(UIButton *)sender {
    self.requestModel.isPublic = 1; //公开
    self.settlementTypeToPublicBtn.selected = YES;
    self.settlementTypeToPrivateBtn.selected = NO;
    
    [self settlementTypeBtn:self.settlementTypeToPublicBtn backgroundColor:[UIColor colorWithHexString:@"f2f6ff"] borderColor:[UIColor colorWithHexString:@"7a97e3"]];
    [self settlementTypeBtn:self.settlementTypeToPrivateBtn backgroundColor:[UIColor whiteColor] borderColor:[UIColor colorWithHexString:@"bebebe"]];
}

- (IBAction)settlementTypeToPrivateBtnClick:(UIButton *)sender {
    self.requestModel.isPublic = 0; //私有
    self.settlementTypeToPrivateBtn.selected = YES;
    self.settlementTypeToPublicBtn.selected = NO;

    [self settlementTypeBtn:self.settlementTypeToPrivateBtn backgroundColor:[UIColor colorWithHexString:@"f2f6ff"] borderColor:[UIColor colorWithHexString:@"7a97e3"]];
    
    [self settlementTypeBtn:self.settlementTypeToPublicBtn backgroundColor:[UIColor whiteColor] borderColor:[UIColor colorWithHexString:@"bebebe"]];
}


- (IBAction)chooseStartDateClcik:(id)sender {
    [self.view endEditing:YES];
    __weak typeof(self)weakSelf = self;
    
    HCGDatePickerAppearance *picker = [[HCGDatePickerAppearance  alloc] initWithDatePickerMode:DatePickerDateMode completeBlock:^(NSDate *date) {
        weakSelf.requestModel.licenceStartDate = [NSString dateStringFrom1970:[date timeIntervalSince1970] formatter:@"yyyy-MM-dd"];
        weakSelf.licenceStartDateTextFiled.text = [NSString dateStringFrom1970:[date timeIntervalSince1970] formatter:@"yyyy年MM月dd日"];
        
        [picker hide];
        
    }];
    
    if (self.requestModel.licenceStartDate) {
        [picker selectDate:[NSString dateFromString:self.requestModel.licenceStartDate formatter:@"yyyy-MM-dd"]];
    }
    
    [picker show];
}

- (IBAction)chooseEndDateClick:(id)sender {
    [self.view endEditing:YES];

    __weak typeof(self)weakSelf = self;
    
    HCGDatePickerAppearance *picker = [[HCGDatePickerAppearance  alloc] initWithDatePickerMode:DatePickerDateMode completeBlock:^(NSDate *date) {
        
        weakSelf.requestModel.licenceEndDate = [NSString dateStringFrom1970:[date timeIntervalSince1970] formatter:@"yyyy-MM-dd"];
        weakSelf.licenceEndDateTextFIled.text = [NSString dateStringFrom1970:[date timeIntervalSince1970] formatter:@"yyyy年MM月dd日"];
        
        [picker hide];
    }];
    
    if (self.requestModel.licenceEndDate) {
        [picker selectDate:[NSString dateFromString:self.requestModel.licenceEndDate formatter:@"yyyy-MM-dd"]];
    }
    
    [picker show];
    
}


- (IBAction)takePhotoBtnClcik:(UIButton *)sender {
    __weak typeof(self) wSelf = self;
    UIImagePickerController *imagePickerVC = [[UIImagePickerController alloc] initWithSourceType:UIImagePickerControllerSourceTypeCamera finish:^(UIImagePickerController *vc, UIImage *image) {
        wSelf.businessLicenseImageView.image = image ;
        [wSelf.takePhotoBtn setImage:nil forState:UIControlStateNormal];
    }];
    
    [self presentViewController:imagePickerVC animated:YES completion:nil];
    
}


#pragma mark - push完善商铺图片 -

- (void)pushToFillInShopPhotos{
    [HSYGoToAuditUtil goAuditFromViewController:self push:YES];
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
